
# 将查询出的结果集转换为json
# 遍历查询集 调用model属性转换成dict
import datetime
# import json
# from django.core import serializers
from django.db.models import Model

# 在定义模型时，创建toDict函数中会用到，目的是将单条数据转化成字典
def model_to_json(self):

    d = {}
    for attr in self._meta.fields:
        obj = getattr(self, attr.name)
        if isinstance(obj, datetime.datetime):
            rs = obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            rs = obj.strftime("%Y-%m-%d")
        elif obj.__class__.__name__ == 'UsersBase':
            rs = obj.id
        # 如果 obj 是特定的类（如 UsersBase 或 CollectMovieDB 在特定条件下），可能会提取其中的某个属性值（如 id 
        # 或 movie_id 等）；对于其他常规类型的值，可能直接将其作为值使用。
        elif obj.__class__.__name__ == 'CollectMovieDB':
            if self.__class__.__name__ == 'MovieComments':
                rs = obj.movie_id
            else:
                rs = obj.title
        elif isinstance(obj, Model):
            rs = obj.__str__()
        elif obj is None:
            rs = ""
        elif obj is True:
            rs = "true"
        elif obj is False:
            rs = "true"
        else:
            # 正常情况下都是这种
            rs = obj
        d[attr.name] = rs

    # d = {'id':"34",'title':"钢铁侠","movie":"变形金刚"}
    return d

# 将查询结果转换成json
def queryset_to_json(queryset):
    obj_arr = []
    for o in queryset:
        obj_arr.append(o.toDict())
    # [
    #     {'id':"34",'title':"钢铁侠","movie":"变形金刚"},
    #     {'id':"34",'title':"钢铁侠","movie":"变形金刚"},
    #     {'id':"34",'title':"钢铁侠","movie":"变形金刚"},
    #     {'id':"34",'title':"钢铁侠","movie":"变形金刚"}
    # ]
    return obj_arr


